import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
const Layout = () => import('@/views/layout')
const Login = () => import('@/views/login')
const NotFound = () => import('@/views/404')
const Home = () => import('@/views/layout/Home')
const Video = () => import('@/views/layout/Video')
const User = () => import('@/views/layout/User')
const Question = () => import('@/views/layout/Question')
const Edit = () => import('@/views/layout/User/Edit')
const Search = () => import('@/views/Search')
const Result = () => import('@/views/Search/result')
const Article = () => import('@/views/article')
const Chat = () => import('@/views/layout/User/chat')
// 解决路由报错问题
// https://github.com/vuejs/vue-router/issues/2881#issuecomment-520554378
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: '/',
        component: Home,
        meta: { iskeepAlive: true }
      },
      {
        path: '/question',
        component: Question
      },
      {
        path: '/user',
        component: User
      },
      {
        path: '/video',
        component: Video
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '*',
    component: NotFound
  },
  {
    path: '/user/edit',
    component: Edit
  },
  {
    path: '/user/chat',
    component: Chat
  },
  {
    path: '/search',
    component: Search
  },
  {
    path: '/search/result',
    component: Result
  },
  {
    path: '/article/:id',
    component: Article
  }
]

const router = new VueRouter({
  routes
})
// 前置导航守卫
/*
1、如果有token,无论去哪个页面都不应该阻拦,直接next()放行即可
2、如果没有token,看看要去往的页面是否需要携带token
3、如果去往的页面需要携带token,就阻拦 跳回login登录页面
4、如果去往的页面不想要携带token,无需阻拦,直接放行即可
 */
const toUrls = ['/user', '/user/edit']
router.beforeEach((to, from, next) => {
  const token = store.state.user.token.token
  if (token) {
    next()
    return
  }
  if (toUrls.includes(to.path)) {
    // next('/login')
    router.push({
      path: '/login',
      query: {
        back: to.path
      }
    })
  } else {
    next()
  }
})

export default router
